package sms

import (
	"encoding/json"
	"fmt"
	"gitchina/kly_service/util"
	_ "github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

type YunpianApi struct {
	phone     string
	tplId     int
	tplParams url.Values
}

type YunpianApiRS struct {
	Code   int     `json:"code"`
	Msg    string  `json:"msg"`
	Count  int     `json:"count"`
	Fee    float32 `json:"fee"`
	Unit   string  `json:"unit"`
	Mobile string  `json:"mobile"`
	Sid    int     `json:"sid"`
}

var apiKey string = "320d5bb939fc5c5989c8b498d1ccf41b"
var apiUrl string = "https://sms.yunpian.com/v2/sms/tpl_single_send.json"

func (api *YunpianApi) Add(key, value string) *YunpianApi {
	api.tplParams.Add(fmt.Sprintf("#%s#", key), value)
	return api
}

func (api *YunpianApi) Send() {
	data_tpl_sms := url.Values{"apikey": {apiKey}, "mobile": {api.phone}, "tpl_id": {strconv.Itoa(api.tplId)}, "tpl_value": {api.tplParams.Encode()}}
	resp, err := http.PostForm(apiUrl, data_tpl_sms)
	if resp != nil {
		defer resp.Body.Close()
	}
	if err == nil {
		if body, err := ioutil.ReadAll(resp.Body); err != nil {
			util.GetLogger().Error("[util-sms] - error:%s", err.Error())
		} else {
			var rs YunpianApiRS
			if err = json.Unmarshal(body, &rs); err != nil {
				util.GetLogger().Error("[util-sms] - error:%s", err.Error())
			} else {
				if rs.Code != 0 {
					util.GetLogger().Error("[util-sms] - error:%s", rs.Msg)
				}
			}
		}
	} else {
		util.GetLogger().Error("[util-sms] - error:%s", err.Error())
	}
}
